/* 
 * Copyright (C) 2001-2003 Jacek Sieka, j_s@telia.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#if !defined(AFX_Client_H__089CBD05_4833_4E30_9A57_BB636231D78E__INCLUDED_)
#define AFX_Client_H__089CBD05_4833_4E30_9A57_BB636231D78E__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "TimerManager.h"
#include "SettingsManager.h"

#include "BufferedSocket.h"
#include "User.h"
#include "CriticalSection.h"
class Client;
#include "ScriptManager.h"

class ClientListener
{
public:
	template<int I>	struct X { enum { TYPE = I }; };
	typedef X<0> Connecting;
	typedef X<1> Connected;
	typedef X<2> BadPassword;
	typedef X<3> UserUpdated;
	typedef X<4> UsersUpdated;
	typedef X<6> Redirect;
	typedef X<7> Failed;
	typedef X<8> GetPassword;
	typedef X<9> HubName;
	typedef X<11> Message;
	typedef X<12> PrivateMessage;
	typedef X<13> UserCommand;
	typedef X<14> HubFull;
	typedef X<15> NickTaken;
	typedef X<16> SearchFlood;
	typedef X<17> ConnectToMe;
	typedef X<19> Supports;
	typedef X<20> CLock;
	typedef X<21> LoggedIn;
	typedef X<22> UserIp;
	typedef X<23> RevConnectToMe;
	typedef X<24> Search;
	typedef X<25> Unknown;
	typedef X<26> ValidateDenied;
	typedef X<26> Quit;
	typedef X<27> RawMessage;
	typedef X<28> Attention;

	virtual void on(Connecting, Client*) throw() { }
	virtual void on(Connected, Client*) throw() { }
	virtual void on(BadPassword, Client*) throw() { }
	virtual void on(UserUpdated, Client*, const User::Ptr&) throw() { }
	virtual void on(UsersUpdated, Client*, const User::List&) throw() { }
	virtual void on(Redirect, Client*, const string&) throw() { }
	virtual void on(Failed, Client*, const string&) throw() { }
	virtual void on(GetPassword, Client*) throw() { }
	virtual void on(HubName, Client*) throw() { }
	virtual void on(Message, Client*, const string&) throw() { }
	virtual void on(PrivateMessage, Client*, const User::Ptr&, const string&) throw() { }
	virtual void on(UserCommand, Client*, int, int, const string&, const string&) throw() { }
	virtual void on(HubFull, Client*) throw() { }
	virtual void on(NickTaken, Client*) throw() { }
	virtual void on(SearchFlood, Client*, const string&) throw() { }
	virtual void on(ConnectToMe, Client*, const string&, const string&) throw() { }
	virtual void on(Supports, Client*, const StringList&) throw() { }
	virtual void on(CLock, Client*, const string&, const string&) throw() { }
	virtual void on(LoggedIn, Client*) throw() { }
	virtual void on(UserIp, Client*, const User::List&) throw() { }
	virtual void on(RevConnectToMe, Client*, const User::Ptr&) throw() { }
	virtual void on(Search, Client*, const string&, int, const string&, int, const string&) throw() { }
	virtual void on(ValidateDenied, Client*) throw() { }
	virtual void on(Quit, Client*, const User::Ptr&) throw() { }

	virtual void on(RawMessage, Client*, const string&) throw() { }
	virtual void on(Attention, Client*) throw() { }
};

class ClientScriptInstance : public ScriptInstance {
public:
	ClientScriptInstance() { L = lua_newthread(ScriptManager::getInstance()->L); }
	//Sulan start svn109
	string formatChatMessage(Client* aClient, string aLine, bool mainChat = true);
	//End
	bool onHubFrameEnter(Client* aClient, const string& aLine);
	bool onClientMessage(Client* aClient, const string& aLine);
	bool clientInfo(Client* aClient, const string& aLine);
};

class Client : public Speaker<ClientListener>, private BufferedSocketListener, private TimerManagerListener, private Flags, public ClientScriptInstance
{
	friend class ClientManager;
public:
	typedef Client* Ptr;
	typedef list<Ptr> List;
	typedef List::iterator Iter;
	// CDM EXTENSION BEGINS
	typedef StringIntMap::reverse_iterator RevSpeedIter;
	// CDM EXTENSION ENDS

	enum SupportFlags {
		SUPPORTS_USERCOMMAND = 0x01,
		SUPPORTS_NOGETINFO = 0x02,
		SUPPORTS_USERIP2 = 0x04,
	};

	enum {
		CONTEXT_RAW_MYINFO = 0x01,
		CONTEXT_RAW_CLIENT = 0x02,
		CONTEXT_RAW_FILELIST = 0x04,
		CONTEXT_RAW_ADLS = 0x08,
		CONTEXT_RAW_MULTIHUB = 0x10,
		CONTEXT_RAW_FAKER = 0x20,
		CONTEXT_RAW_CONNECTION_TROUBLE = 0x40,
		CONTEXT_RAW_BAD_ISP = 0x80,
		CONTEXT_RAW_POSSIBLE_FLOODER = 0x100,
		CONTEXT_RAW_FAKE_SHARE = 0x200,
		CONTEXT_RAW_GPL_BREAKING_SCUM = 0x400,
		CONTEXT_ACTIVE_USING_PASSIVE = 0x800,
		// pothead extension ends (dc++ code)
		CONTEXT_MASK = CONTEXT_RAW_MYINFO | CONTEXT_RAW_CLIENT | CONTEXT_RAW_FILELIST | CONTEXT_RAW_ADLS | 
						CONTEXT_RAW_MULTIHUB | CONTEXT_RAW_FAKER | CONTEXT_RAW_CONNECTION_TROUBLE | 
						CONTEXT_RAW_BAD_ISP | CONTEXT_RAW_POSSIBLE_FLOODER | CONTEXT_RAW_FAKE_SHARE | 
						CONTEXT_RAW_GPL_BREAKING_SCUM | CONTEXT_ACTIVE_USING_PASSIVE,
	};

	User::NickMap& lockUserList() throw() { cs.enter(); return users; };
	void unlockUserList() throw() { cs.leave(); };

	bool isConnected() { return socket->isConnected(); };
	void disconnect() throw();
	void myInfo();
	// CDM EXTENSION BEGINS
	bool startChecking() {
		if(checker.isChecking() || !getOp()) { return false; }
		checker.setKeepChecking(true);
		checker.startCheck(this);
		return true;
	};
	void startCheckOnConnect() {
		if(!checker.isChecking()) {
			checker.setCheckOnConnect(true);
			checker.startCheck(this);
		}
	}
	void stopChecking() {
		checker.cancel();
	};
	bool isChecking() {
		return checker.isChecking();
	};
	class ThreadedCheck : public Thread
	{	
		public:
			ThreadedCheck() : keepChecking(false), initialSweepComplete(false), inThread(false), checkOnConnect(false) { };
			virtual ~ThreadedCheck() { join(); }

			GETSET(bool, keepChecking, KeepChecking);
			GETSET(bool, checkOnConnect, CheckOnConnect);
			bool isChecking() { return inThread; }
			void startCheck(Client* c);
			virtual int run();
			void cancel() {
				keepChecking = inThread = false;
				stop();
			}

			Client* client;
		private:
			bool initialSweepComplete;
			bool inThread;
	}checker;
	// CDM EXTENSION ENDS
	
	void refreshUserList(bool unknownOnly = false);

#define checkstate() if(state != STATE_CONNECTED) return

	void sendRaw(const string& aRaw) { send(aRaw); }
	void validateNick(const string& aNick) { send("$ValidateNick " + aNick + "|"); }
	void key(const string& aKey) { send("$Key " + aKey + "|"); };	
	void version(const string& aVersion) { send("$Version " + aVersion + "|"); };
	void getNickList() { send("$GetNickList|"); }
	void password(const string& aPass) { send("$MyPass " + aPass + "|"); };
	void getInfo(User::Ptr aUser) { checkstate(); if(getUserInfo()) send("$GetINFO " + aUser->getNick() + " " + getNick() + "|"); };
	void getInfo(User* aUser) { checkstate(); if(getUserInfo())send("$GetINFO " + aUser->getNick() + " " + getNick() + "|"); };
	void sendMessage(const string& aMessage) { checkstate(); send("<" + getNick() + "> " + Util::validateMessage(aMessage, false) + "|"); }
	void sendMessageRaw(const string& aMessage) { send(aMessage); }
	// CDM EXTENSION BEGINS
	void userIp(User::Ptr aUser) { send("$UserIP " + aUser->getNick() + "|"); };
	//Sulan
	void reloadFavHubs();
	//Sulan start svn 168
	User::Ptr findUser(int64_t aShare, const string& aIp, const string& aEmail, const string& aConnection, const string& aHubCount, bool forFilelist);
	//End
	
	// CDM EXTENSION ENDS

	void search(int aSizeType, int64_t aSize, int aFileType, const string& aString);
	void searchResults(const string& aResults) { send(aResults); };
	
	void connectToMe(const User::Ptr& aUser) {
		checkstate(); 
		dcdebug("Client::connectToMe %s\n", aUser->getNick().c_str());
		send("$ConnectToMe " + aUser->getNick() + " " + getLocalIp() + ":" + Util::toString(SETTING(IN_PORT)) + "|");
	}
	void connectToMe(User* aUser) {
		checkstate(); 
		dcdebug("Client::connectToMe %s\n", aUser->getNick().c_str());
		send("$ConnectToMe " + aUser->getNick() + " " + getLocalIp() + ":" + Util::toString(SETTING(IN_PORT)) + "|");
	}
	void privateMessage(const User::Ptr& aUser, const string& aMessage) {
		privateMessage(aUser->getNick(), aMessage);
	}
	void privateMessage(User* aUser, const string& aMessage) {
		privateMessage(aUser->getNick(), aMessage);
	}
	void privateMessage(const string& aNick, const string& aMessage) {
		checkstate(); 
		send("$To: " + aNick + " From: " + getNick() + " $" + Util::validateMessage(aMessage, false) + "|");
	}
	void supports(const StringList& feat) { 
		string x;
		for(StringList::const_iterator i = feat.begin(); i != feat.end(); ++i) {
			x+= *i + ' ';
		}
		send("$Supports " + x + '|');
	}
	void revConnectToMe(const User::Ptr& aUser) {
		checkstate(); 
		dcdebug("Client::revConnectToMe %s\n", aUser->getNick().c_str());
		send("$RevConnectToMe " + getNick() + " " + aUser->getNick() + "|");
	}
	void revConnectToMe(User* aUser) {
		checkstate(); 
		dcdebug("Client::revConnectToMe %s\n", aUser->getNick().c_str());
		send("$RevConnectToMe " + getNick() + " " + aUser->getNick() + "|");
	}
	// CDM EXTENSION BEGINS
	//void sendDebugMessage(const string& aLine);
	string getRawCommand(const int aRawCommand) {
		switch(aRawCommand) {
			case 1: return rawOne;
			case 2: return rawTwo;
			case 3: return rawThree;
			case 4: return rawFour;
			case 5: return rawFive;
			case 6: return rawSix;
			case 7: return rawSeven;
			case 8: return rawEight;
			case 9: return rawNine;
			case 10: return rawTen;
		}
		return Util::emptyString;
	};
	string getNickFromUserIp(const string& aUserIp) throw();
	void attention() {
		fire(ClientListener::Attention(), this);
	}

	string getSpeedStats();
	// CDM EXTENSION ENDS

	void send(const string& aLine) throw();
	void send(const char* aBuf, int aLen) throw();

	void kick(const User::Ptr& aUser, const string& aMsg);
	void kick(User* aUser, const string& aMsg);
	
	void opForceMove(const User::Ptr& aUser, const string& aServer, const string& aMsg) {
		checkstate(); 
		dcdebug("Client::opForceMove\n");
		send("$OpForceMove $Who:" + aUser->getNick() + "$Where:" + aServer + "$Msg:" + aMsg + "|");
	}

	void connect(const string& aAddressPort);
	
	void updated(User::Ptr& aUser) {
		fire(ClientListener::UserUpdated(), this, aUser);
	}

	const string& getName() const { return name; };
	const string& getAddress() const { return address; };
	const string& getAddressPort() const { return addressPort; };
	short getPort() const { return port; };

	const string& getIp() {	return socket->getIp().empty() ? getAddress() : socket->getIp(); };
	string getIpPort() { return port == 411 ? getIp() : getIp() + ':' + Util::toString(port); };

	int getUserCount() throw() {
		Lock l(cs);
		return users.size();
	}

	int64_t getAvailable() throw() {
		Lock l(cs);
		int64_t x = 0;
		for(User::NickIter i = users.begin(); i != users.end(); ++i) {
			x+=i->second->getBytesShared();
		}
		return x;
	}

	string getRandomNick() {
		User::NickMap::size_type elements = getUserCount();
		if (elements == 0) return Util::emptyString;

		elements = Util::rand(0, elements - 1);
		User::NickMap::const_iterator cu = users.begin();
		for (User::NickMap::size_type i = 0; i < elements; ++i) ++cu;
		return cu->first;
	}

	static string getCounts() {
		return Util::toString(counts.normal) + '/' + Util::toString(counts.registered) + '/' + Util::toString(counts.op);
	}

	string getLocalIp() { 
		if(!SETTING(SERVER).empty()) {
			return Socket::resolve(SETTING(SERVER));
		}
		if(me && !me->getIp().empty())
			return me->getIp();

		if(socket == NULL)
			return Util::getLocalIp();
		string tmp = socket->getLocalIp();
		if(tmp.empty())
			return Util::getLocalIp();
		return tmp;
	}

	const string& getDescription() const { return description.empty() ? SETTING(DESCRIPTION) : description; };
	void setDescription(const string& aDesc) { description = aDesc; };

	string getLocalSearchIp() { 
		return SETTING(SEARCH_SERVER).empty() ? getLocalIp() : Socket::resolve(SETTING(SEARCH_SERVER));
	}

	string getDescriptionFormat() const;

	bool getOp() { return me ? me->isSet(User::OP) : false; };

	GETSET(User::Ptr, me, Me);
	GETSET(string, nick, Nick);
	GETSET(string, defpassword, Password);
	GETSET(int, supportFlags, SupportFlags);
	GETSET(bool, userInfo, UserInfo);
	GETSET(bool, registered, Registered);
	GETSET(bool, firstHello, FirstHello);
	// CDM EXTENSION BEGINS FAVS
	//Add to favs
	GETSET(string, rawOne, RawOne);
	GETSET(string, rawTwo, RawTwo);
	GETSET(string, rawThree, RawThree);
	GETSET(string, rawFour, RawFour);
	GETSET(string, rawFive, RawFive);
	GETSET(string, rawSix, RawSix);
	GETSET(string, rawSeven, RawSeven);
	GETSET(string, rawEight, RawEight);
	GETSET(string, rawNine, RawNine);
	GETSET(string, rawTen, RawTen);
	GETSET(string, opChat, OpChat);
	GETSET(bool, sendUserIp, SendUserIp);
	GETSET(bool, checkClients, CheckClients);
	GETSET(bool, checkFilelists, CheckFilelists);
	GETSET(bool, checkFakeShare, CheckFakeShare);
	void addLine(const string& line) {
		fire(ClientListener::Message(), this, Util::validateMessage(line, true));
	}
	GETSET(bool, checkOnConnect, CheckOnConnect);
	GETSET(bool, showIPs, ShowIPs);
	GETSET(string, countryCodeCheck, CountryCodeCheck);
	GETSET(int, countryCodeRaw, CountryCodeRaw);
	GETSET(string, protectedUsers, ProtectedUsers);
	GETSET(bool, hideShare, HideShare);
	//Sulan start 28
	GETSET(string, trigger, Trigger);
	//Sulan start svn86
	GETSET(bool, logChat, LogChat);
	//End
	// pothead starts
	GETSET(string, hubMessage, HubMessage);
	GETSET(bool, useMyinfoDetect, UseMyinfoDetect);
	GETSET(string, regStatus, RegStatus);
	//Sulan start svn?
	GETSET(string, disableRaws, DisableRaws);
	GETSET(bool, disableSearchSelect, DisableSearchSelect);
	bool getDisableRaws(const int context);
	// pothead ends
	// CDM EXTENSION ENDS
	void connect();

	void onLine(const string& aLine) throw();		//sure, it's ugly...
private:
	enum States {
		STATE_CONNECT,
		STATE_LOCK,
		STATE_HELLO,
		STATE_CONNECTED
	} state;

	enum {
		COUNT_UNCOUNTED,
		COUNT_NORMAL,
		COUNT_REGISTERED,
		COUNT_OP
	};

	string address;
	string addressPort;
	short port;
	string description_format;

	string name;
	string description;

	BufferedSocket* socket;
	u_int32_t lastActivity;
	int prevslots;

	CriticalSection cs;

	User::NickMap users;

	struct Counts {
		Counts(long n = 0, long r = 0, long o = 0) : normal(n), registered(r), op(o) { }
		volatile long normal;
		volatile long registered;
		volatile long op;
		bool operator !=(const Counts& rhs) { return normal != rhs.normal || registered != rhs.registered || op != rhs.op; }
	};

	static Counts counts;

	Counts lastCounts;

	int countType;
	bool reconnect;
	u_int32_t lastUpdate;
	
	typedef list<pair<string, u_int32_t> > FloodMap;
	typedef FloodMap::iterator FloodIter;
	FloodMap seekers;
	FloodMap flooders;

	void updateCounts(bool aRemove);

	Client();	
	virtual ~Client() throw();

	// Dummy
	Client(const Client&);
	Client& operator=(const Client&);

	void clearUsers();
	
	// TimerManagerListener
	virtual void on(TimerManagerListener::Second, u_int32_t aTick) throw();

	// BufferedSocketListener
	virtual void on(BufferedSocketListener::Line, const string& aLine) throw();
	virtual void on(BufferedSocketListener::Failed, const string& aLine) throw();
	virtual void on(BufferedSocketListener::Connected) throw();
	virtual void on(BufferedSocketListener::Connecting) throw(){fire(ClientListener::Connecting(), this);}

public:
	string findNickIp(const string& aHint, bool aIsIp);
	int countExistingIps(const string& aIP);
};

#endif // !defined(AFX_Client_H__089CBD05_4833_4E30_9A57_BB636231D78E__INCLUDED_)

/**
 * @file
 * $Id: Client.h 329 2005-08-30 21:06:02Z Pothead $
 */